<script lang="ts" setup>
// 获取顶部安全距离
import type { UniFilePicker, UniFilePickerOnDelete, UniFilePickerOnSelect } from "@uni-helper/uni-ui-types";
import { onMounted, ref, watch } from "vue";
import type { UploadAnimal } from "@/types/upload";
import AddTagPopup from "@/pages/upload/components/AddTagPopup.vue";
import { useCategoryStore } from "@/stores/category";
import { uploadRules } from "@/utils/verify";
import { useUploadStore } from "@/stores/upload";
import { uploadAnimalsApi } from "@/api/upload";
import { IMessage } from "@/components/aw-message/message";
import { useUserStore } from "@/stores/user";
import { getUserUploadCountApi } from "@/api/user";
import { onShow } from "@dcloudio/uni-app";

const { safeAreaInsets } = uni.getSystemInfoSync()
const userStore = useUserStore()
const uploadStore = useUploadStore()
const uploadData = ref<UploadAnimal>({} as UploadAnimal) //上传准备数据
uploadData.value = uploadStore.uploadData // 初始化数据
watch(uploadStore.uploadImg, (newValue) => {
})
//分类数据
const categoryStore = useCategoryStore()
const categoryList = categoryStore.categoryList.map((item) => {
  return {
    text: item.name,
    value: item.name
  }
})
/**
 * 选择图片时
 * @param event
 */
const onSelectImg: UniFilePickerOnSelect = async (event) => {

  // 过滤掉size大于5mb的数据
  const tempFiles = event.tempFiles.filter((item) => item.size < 1024 * 1024 * 2 && item.image!.height > 0 && item.image!.width > 0)
  tempFiles.length < event.tempFiles.length ? uni.showToast({
    title: '图片超过2MB或格式错误',
    icon: 'none',
    duration: 3000
  }) : ''
  if (uploadStore.uploadImg.length > 0 && tempFiles.length === 0) {
    uploadStore.uploadImg = uploadStore.uploadImg.slice(0, uploadStore.uploadImg.length);
    return
  } else if (uploadStore.uploadImg.length > 0 && tempFiles.length > 0) {
    uploadStore.uploadImg = uploadStore.uploadImg.concat(tempFiles)
  } else {
    uploadStore.uploadImg = tempFiles // 初始值
  }

  // 准备发送
  for (let i = 0; i < tempFiles.length; i++) {
    // 上传图片
    const uploadTask = uni.uploadFile({
      url: '/upload',
      filePath: tempFiles[i].path,
      name: 'file',
      success: (uploadFileRes) => {
        const res = JSON.parse(uploadFileRes.data)
        console.log(res)
        if (res.code!.toString() !== '1') {
          if (uploadStore.uploadImg.length === 1) {
            uploadStore.uploadImg = []
          }
          uploadStore.uploadImg = uploadStore.uploadImg.slice(i, 1);
          return IMessage({
            type: 'error',
            content: res.message,
            showIcon: true
          })
        }
        if (uploadData.value.imgList) {
          uploadData.value.imgList.push({ uid: tempFiles[i].uuid, url: res.data })
        } else {
          uploadData.value.imgList = [{ uid: tempFiles[i].uuid as string, url: res.data as string }]
        }
      }
    }
    )

    uploadTask.onProgressUpdate((res) => {
      /*      // 测试条件，取消上传任务。
            if (res.progress > 50) {
              uploadTask.abort();
            }*/
    })
  }

}
/**
 * 移除已选择的图片
 */
const onDeleteImg: UniFilePickerOnDelete = (event) => {
  let uuid = event.tempFile.uuid
  uploadData.value.imgList = uploadData.value.imgList?.filter((item: any) => item.uid !== uuid)
}

/*上传表单数据*/
const uploadForm = ref()
// 保护级别
const protectLevel = [
  {
    text: '一级保护动物',
    value: 1
  },
  {
    text: '二级保护动物',
    value: 2
  },
  {
    text: '三级保护动物',
    value: 3
  },
  {
    text: '可爱的动物',
    value: 4
  }
]
// 输入框样式
const inputStyle = {
  borderColor: "rgb(0,0,0,0)",
  backgroundColor: 'rgb(255,255,255,0.3)',
}
//点击添加tag
const tagPopup = ref()
const showTagPopup = () => {
  tagPopup.value.open()
}
// 点击取消
const onCancelTag = () => {
  tagPopup.value.close()
}
/**
 * 删除tag
 * @param index 被删除的索引
 */
const onDeleteTag = (index: number) => {
  // 删除
  uploadData.value.tags.splice(index, 1)
}
/**
 * 添加tag
 * @param tag tag值
 */
const onAddTag = (tag: string) => {
  if (!uploadData.value.tags) {
    return uploadData.value.tags = [tag]
  }
  if (uploadData.value.tags.includes(tag)) {
    return uni.showToast({ title: '不能添加两个相同的标签', icon: 'none', duration: 2000 })
  }
  uploadData.value.tags.push(tag)
  uni.hideKeyboard()
}
/**
 * 点击确定
 */
const onConfirmTag = () => {
  tagPopup.value.close()
}

// 上传前确认

const checkUpload = ref()
const onCheckUpload = () => {
  console.log(userStore.userInfoData)
  if (userStore.userInfoData === undefined) {
    popupToLogin.value.open()
    return uni.showToast({ title: '请先登录', icon: 'none', duration: 2000 })
  }
  checkUpload.value.open()
}
// 取消上传
const onCancelUpload = () => {
  checkUpload.value.close()
}
// 点击上传
const onSubmit = () => {
  checkUpload.value.close()
  // 判断图片数据
  if (uploadData.value.imgList?.length < 1 || uploadData.value.imgList === undefined) {
    return uni.showToast({ title: '请上传至少一张图片', icon: 'none', duration: 2000 })
  }
  // 校验表单
  if (!uploadData.value.description || !uploadData.value.classification) {
    return uni.showToast({ title: '请将表单填写完整', icon: 'none', duration: 2000 })
  }
  uploadForm.value.validate().then(async (res: any) => {
    // 发送
    uni.showLoading({ title: '上传中...' })
    await uploadAnimalsApi(uploadData.value)
    uni.hideLoading()
    await uni.showToast({ title: '上传成功', icon: 'success', duration: 2000 })
    await getUploadCount()
  }).catch((err: any) => {
    checkUpload.value.close()
    uni.showToast({ title: err.data.message, icon: 'none', duration: 2000 })
  })
}

// 点击保存
const onSaveUploadData = () => {
  if (userStore.userInfoData === undefined) {
    popupToLogin.value.open()
    return uni.showToast({ title: '请先登录', icon: 'none', duration: 1500 })
  }
  // 保存数据到本地
  uploadStore.uploadData = uploadData.value
  uni.showToast({ title: '已保存到本地', icon: 'success', duration: 1500 })
}
/**
 * 用户清空待上传数据
 */
const onClearUpload = () => {
  clearUpload.value.open()
}
const clearUpload = ref()
const onCancelClear = () => {
  clearUpload.value.close()
}
const onConfirmClear = () => {
  clearUpload.value.close()
  if (Object.keys(uploadStore.uploadData).length === 0 && uploadStore.uploadImg.length === 0) {
    return IMessage({
      content: '暂无待上传数据',
      type: 'warning',
      duration: 2500
    })
  }
  uploadStore.uploadData = {}
  uploadStore.uploadImg = []
  uploadData.value = {}
  IMessage({
    content: '已清空待上传数据',
    type: 'success',
    duration: 2500
  })
}

const popupToLogin = ref()
const gotoLogin = () => {
  popupToLogin.value.close()
  uni.navigateTo({ url: '/subPkg/login/login' })
}

/**
 * 获取用户剩余上传次数
 */
const uploadCount = ref(0)
const getUploadCount = async () => {
  const res = await getUserUploadCountApi()
  uploadCount.value = res.data
}
onShow(() => {
  if (userStore.userInfoData) {
    getUploadCount()
  }
})
</script>

<template>
  <view :style="{ paddingTop: `${safeAreaInsets?.top}` + 'px', paddingBottom: `${safeAreaInsets?.bottom}` + 'px' }"
    class="upload-container">
    <view class="upload-title">上传数据</view>
    <view class="upload-box">
      <view class="upload-item upload-item-img" style="min-height: 60px">
        <view v-if="userStore.userInfoData" class="example-body">
          <uni-file-picker ref="uploadImg" v-model="uploadStore.uploadImg" :auto-upload="false" file-mediatype="image"
            limit="5" title="单张小于2MB" @delete="onDeleteImg" @select="onSelectImg">
          </uni-file-picker>
        </view>
        <view v-else class="flex justify-center align-center flex-column padding-sm"
          style="width: 100%;height: 100%;gap: 10px">
          <text class="text-gray">登录后可使用该功能哟~</text>
          <button class="cu-btn bg-gradual-awGreen lg round " @click="popupToLogin.open()">去登录</button>
        </view>
      </view>
      <text v-if="userStore.userInfoData" class="text-sm text-red margin-top-sm padding-left-sm"
        style="align-self: flex-start">本周剩余上传次数：{{ uploadCount }}
      </text>
      <view class="upload-item upload-item-form">
        <uni-forms ref="uploadForm" :modelValue="uploadData" :rules="uploadRules" label-position="top"
          label-width="80px" validate-trigger="bind">
          <uni-forms-item label="名称" name="name" required>
            <view class="custom-input">
              <uni-easyinput v-model="uploadData.name" :clear-size="20" :input-border="false" :maxlength="18"
                :styles="inputStyle" :trim="true" placeholder="请输入动物名" primary-color="#39c5bb" />
            </view>
          </uni-forms-item>
          <uni-forms-item label="分类" name="category" required>
            <view class="custom-input">
              <uni-data-select v-model="uploadData.classification" :localdata="categoryList"
                :style="{ backgroundColor: 'rgba(255,255,255,0.3)', border: 'none' }" placeholder="请选择动物类别" />
            </view>
          </uni-forms-item>
          <uni-forms-item label="保护级别" required>
            <view class="custom-input">
              <uni-data-select v-model="uploadData.protectionLevel" :localdata="protectLevel"
                :style="{ backgroundColor: 'rgba(255,255,255,0.3)' }" placeholder="请选择保护级别" />
            </view>
          </uni-forms-item>
          <uni-forms-item label="栖息地分布" name="distribution" required>
            <view class="custom-input" style="width: 80%">
              <uni-easyinput v-model="uploadData.distribution" :styles="inputStyle" placeholder="请选择分布"
                primary-color="#39c5bb" />
            </view>
          </uni-forms-item>
          <uni-forms-item label="简要描述" name="desc" required>
            <view class="custom-input" style="height: auto;width: 100%;overflow: hidden">
              <uni-easyinput v-model="uploadData.description" :auto-height="true" :clearable="false" :disabled="false"
                :inputBorder="false" :maxlength="500" :styles="inputStyle" :trim="true" placeholder="请输入该动物的简述"
                primary-color="#39c5bb" type="textarea">
                <template v-slot:right>
                  <text style="margin-right: 10px;color: rgba(10,10,10,0.32);position: absolute;bottom: 0;right: 0">
                    {{ uploadData.description ? uploadData.description.length : 0 }}/500
                  </text>
                </template>
              </uni-easyinput>
            </view>
          </uni-forms-item>
          <!--       标签   -->
          <uni-collapse :item-style="{ backgroundColor: 'red' }" class="form-tag">
            <uni-collapse-item :border="false" :open="true" :show-animation="true" class="add-tag" title-border="none">
              <template v-slot:title>
                <view class="tag-title">{{ uploadData.tags?.length > 0 ? '已选标签' : '添加标签' }}</view>
              </template>

              <view class="tag-list">
                <view v-for="item in uploadData.tags" :key="item" class="add-tag-btn">
                  {{ item }}
                </view>
                <view class="add-tag-btn" hover-class="add-tag-btn-hover" @click="showTagPopup">
                  <uni-icons color="#ffffff" size="20" type="plus"></uni-icons>
                  {{ uploadData.tags?.length > 0 ? '修改标签' : '添加标签' }}
                </view>
              </view>
            </uni-collapse-item>
          </uni-collapse>
        </uni-forms>
      </view>
      <view class="footer">
        <view class="save margin-left-sm" hover-class="save-hover" @click="onClearUpload">
          <view class="cuIcon-refresh text-shadow text-awGreen" style="font-size: 56rpx"></view>
        </view>
        <view class="save" hover-class="save-hover" @click="onSaveUploadData">
          <view class="cuIcon-file text-shadow text-awGreen " style="font-size: 56rpx"></view>
        </view>
        <view :class="['submit', userStore?.userInfoData ? ' bg-gradual-awGreen' : 'bg-disabled']"
          @click="onCheckUpload">上传
          <text class="cuIcon-upload" style="font-size: 40rpx"></text>
        </view>
      </view>
    </view>
  </view>

  <!--  底部弹出层-->
  <uni-popup ref="tagPopup" type="bottom" style="z-index: 9999">
    <view class="bg-white">
      <add-tag-popup :tag-list="uploadData.tags" @addTag="onAddTag" @cancel="onCancelTag" @confirm="onConfirmTag"
        @deleteTag="onDeleteTag"></add-tag-popup>
    </view>
  </uni-popup>

  <!--  上传确认-->
  <uv-modal ref="checkUpload" :closeOnClickOverlay="false" :zoom="true" title="提示">
    <template v-slot:default>
      <view class="text-df"> 上传的图片或文字内容不能违反国家法律规定，否则不但审核不会通过，还会进行
        <text class="text-red">封号</text>
        处理。
      </view>
    </template>
    <template v-slot:confirmButton>
      <view class="flex padding-sm justify-center align-center" style="width: 100%;gap: 40px">
        <button class="cu-btn round line-gray lg" @click="onCancelUpload">取消</button>
        <button class="cu-btn round bg-gradual-awGreen lg" @click="onSubmit">确定上传</button>
      </view>
    </template>
  </uv-modal>

  <!--  确认清除-->
  <uv-modal ref="clearUpload" :closeOnClickOverlay="false" :zoom="true" title="是否确认清空当前数据">
    <template v-slot:confirmButton>
      <view class="flex padding-sm justify-center align-center" style="width: 100%;gap: 40px">
        <button class="cu-btn round bg-gray lg" @click="onCancelClear">取消</button>
        <button class="cu-btn round bg-gradual-awGreen lg" @click="onConfirmClear">确定</button>
      </view>
    </template>
  </uv-modal>
  <uni-popup ref="popupToLogin" type="dialog">
    <uni-popup-dialog confirm-text="前往登录" content="是否前往登录？" title="提示" type="info"
      @confirm="gotoLogin"></uni-popup-dialog>
  </uni-popup>
</template>

<style lang="scss" scoped>
/* #ifdef H5 */
body {
  min-height: 800px;
}

/* #endif */
.upload-container {
  width: 100%;
  background: linear-gradient(45deg, #eee, #3ebed3, #39c5bb);
  z-index: 1;

  .upload-title {
    color: #eee;
    font-size: 20px;
    z-index: 999;
    opacity: 1;
    position: fixed;
    top: 0;
    /* #ifdef H5 */
    padding: 20rpx 0 10rpx 10rpx;
    /* #endif */

    /* #ifndef H5 */
    padding: 80rpx 0 10rpx 10rpx;
    /* #endif */

    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgba(57, 197, 187, 0);
    backdrop-filter: blur(10px);
  }

  .upload-box {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-direction: column;
    z-index: 2;
    opacity: 1;
    padding-top: 40px;

    .custom-input {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      width: 450rpx;
      height: 100rpx;
      //overflow: hidden;
      border-radius: 10rpx;
    }

    .upload-item {
      opacity: 1;
      width: 95%;
      background: rgba(255, 255, 255, 0.3);
      border-radius: 20rpx;
      margin-top: 20rpx;
      z-index: 99;
      padding: 20rpx;
    }

    .upload-item-img {}

    .upload-item-form {}

    // 标签样式
    .form-tag {
      border-radius: 10px;
      background-color: rgba(255, 255, 255, 0.3);
      margin-bottom: 150rpx;

      .add-tag {
        display: flex;
        align-items: center;
        flex-direction: column;
        max-height: 200px;

        .tag-title {
          margin-top: 5px;
          padding: 5px;
          font-size: 14px;
          color: #8d8d8d;
          opacity: 1;
        }

        .tag-list {
          display: flex;
          justify-content: flex-start;
          padding: 10px;
          align-items: center;
          flex-wrap: wrap;
          border-radius: 10px;

          .add-tag-btn {
            position: relative;
            height: 60rpx;
            min-width: 80rpx;
            background: #39c5bb;
            border-radius: 15px;
            margin: 10px 10px 10px 0;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #ffffff;
            font-size: 13px;
            z-index: 99;
            opacity: 1;
            padding: 5px 10px;
          }

          .add-tag-btn-hover {
            background-color: #3ebed3;
          }
        }

        .tag {
          margin: 8px;
        }
      }
    }

    .footer {
      z-index: 9999;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 40rpx 20rpx;
      /* #ifdef MP-WEIXIN */
      padding-bottom: 0rpx;
      /* #endif */
      width: 100%;
      gap: 10rpx;
      position: fixed;
      bottom: 0;
      left: 0;
      backdrop-filter: blur(10px);

      .save {
        width: 80rpx;
        height: 80rpx;
        background-color: rgba(255, 255, 255, 0.3);
        border-radius: 20rpx;
        display: flex;
        justify-content: center;
        align-items: center;

        image {
          width: 65%;
          height: 65%;
          object-fit: cover;
        }
      }

      .submit {
        width: 70%;
        height: 80rpx;
        border-radius: 25px;
        //margin: 20px 40rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #ffffff;
        font-size: 40rpx;
        z-index: 99;
        opacity: 1;
        gap: 18rpx;
      }

      .submit-hover {
        background-color: #00bf9d;
      }
    }
  }
}

.bg-disabled {
  background: #E4E5E7FF;
  color: #98999CFF !important;
}

.uni-select__input-placeholder {
  color: #999999 !important;
}
</style>
